package com.cv.system.service.logger;

import cn.hutool.core.collection.CollUtil;
import com.cv.framework.common.pojo.PageResult;
import com.cv.framework.common.utils.object.BeanUtils;
import com.cv.framework.common.utils.string.StrUtil;
import com.cv.framework.security.core.utils.SecurityFrameworkUtil;
import com.cv.system.api.logger.dto.OperateLogCreateReqDTO;
import com.cv.system.controller.system.logger.vo.operateLog.OperateLogPageReqVO;
import com.cv.system.controller.system.logger.vo.operateLog.OperateLogRespVO;
import com.cv.system.dal.dataobject.logger.SystemOperateLogDO;
import com.cv.system.dal.mapper.logger.SystemOperateLogMapper;
import com.cv.system.service.user.SystemUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

import static com.cv.system.dal.dataobject.logger.SystemOperateLogDO.JAVA_METHOD_ARGS_MAX_LENGTH;
import static com.cv.system.dal.dataobject.logger.SystemOperateLogDO.RESULT_MAX_LENGTH;

/**
 * 系统操作日志业务层接口实现类
 *
 * @author Charles_XDXD
 */
@Service
public class SystemOperateLogServiceImpl implements SystemOperateLogService {

    @Resource
    private SystemOperateLogMapper systemOperateLogMapper;

    @Resource
    private SystemUserService systemUserService;

    @Override
    public void createOperateLog(OperateLogCreateReqDTO operateLogCreateReqDTO) {
        SystemOperateLogDO log = BeanUtils.toBean(operateLogCreateReqDTO, SystemOperateLogDO.class);
        log.setJavaMethodArgs(StrUtil.maxLength(log.getJavaMethodArgs(), JAVA_METHOD_ARGS_MAX_LENGTH));
        log.setResultData(StrUtil.maxLength(log.getResultData(), RESULT_MAX_LENGTH));
        log.setCreator(SecurityFrameworkUtil.getLoginUserId());
        log.setUpdater(SecurityFrameworkUtil.getLoginUserId());
        systemOperateLogMapper.insert(log);
    }

    @Override
    public PageResult<OperateLogRespVO> getOperateLogPage(OperateLogPageReqVO operateLogPageReqVO) {
        Collection<Long> ids = null;
        if (cn.hutool.core.util.StrUtil.isNotEmpty(operateLogPageReqVO.getUserNickname())) {
            ids = systemUserService.queryUserIdsByNickname(operateLogPageReqVO.getUserNickname());

            if (CollUtil.isEmpty(ids)) {
                return PageResult.empty();
            }
        }

        PageResult<OperateLogRespVO> pageResult = BeanUtils.toBean(systemOperateLogMapper.selectPage(operateLogPageReqVO, ids), OperateLogRespVO.class);

        if (CollUtil.isNotEmpty(pageResult.getList())) {
            pageResult.getList().forEach(item -> {
                item.setUserNickname(systemUserService.queryNicknameByUserId(item.getUserId()));
            });
        }

        return pageResult;
    }

}
